<?php defined('SYSPATH') or die('No direct access allowed.');

/**
 * Booklet
 */
class Model_Booklet extends ORM {

	protected $_has_many = array(
		'pictures' => array(
			'model' => 'picture',
			'foreign_key' => 'booklet_id',
		),
		'categories' => array(
			'model' => 'category',
			'through' => 'booklets_categories',
		),
	);

	protected $_has_one = array(
		'user_booklet' => array(
			'model'       => 'user_booklet',
			'foreign_key' => 'booklet_id'
		),
	);
	

	public function rules()
	{
		return array(
			'name' => array(
				array('not_empty'),
				array(array($this, 'name_available')),
			),
		);
	}

	public function name_available($name)
	{
		(bool) DB::select(array('COUNT("*")', 'total_count'))
			->from($this->_table_name)
			->where('name', '=', $name)
			->where($this->_primary_key, '!=', $this->pk())
			->execute($this->_db)
			->get('total_count');
	}

	public function get_image()
	{
		if ($this->frontcover != 0)
		{
			$pictures = $this->pictures->where('id', '=', $this->frontcover)->find_all();
		}
		else
		{
			$pictures = $this->pictures->limit(1)->find_all();
		}
		foreach ($pictures as $picture)
		{
			return $picture->image;
		}
		return NULL;
	}

	public function get_category_string()
	{
		$category_list = $this->categories->find_all();
		$category_string = "";
		foreach ($category_list as $category)
		{
			if (empty($category_string))
			{
				$category_string = $category->name;
			}
			else
			{
				$category_string = $category_string.','.$category->name;
			}
		}
		return $category_string;
	}
	

} // End Booklet

